package com.money.demo.common;

import java.util.Random;

public class MoneyBuilder {

    private Double total;
    private int temp;
    private int count;

    public MoneyBuilder(Double total, int count) {
        this.total = total;
        this.count = count;
        this.temp = (int)(total * 100);
    }

    public static void main(String[] args) {
        MoneyBuilder builder=new MoneyBuilder(100.0, 30);


        double all=0.0;

        for(int i=0; i<30; i++){
            double num=builder.getRandomMoney(20.0);
            all+=num;

            System.out.println(num);
        }

        System.out.println(all);

    }



    public double getRandomMoney() {
        return getRandomMoney(null);
    }


    public double getRandomMoney(Double max) {
        if(max!=null) {
            if (temp / count > max * 100) {
                throw new RuntimeException("每个红包的金额已大于红包总额");
            }

            //如果每个红包设置的最大金额刚好能够发完
            if (temp / count == max * 100) {
                int val = temp / count;
                temp = temp - val;
                count--;
                return val/100.0;
            }
        }

        int val;
        // 当红包总额只够发最少金额的红包的时候，保证至少剩余的红包里每一个红包都有钱
        if(count !=0 && temp / count == 1) {
            val = 1;
            temp = temp - val;
            count--;
            return val/100.0;
        }

        if(count <= 0) { //红包已发完
            val = 0;
        }else if(count == 1) { //只剩一个红包未发的时候
            val = temp;
        }else {
            int left; //剩下的金额
            while(true) {

                //随机生成当前金额的随机数 （temp/count)使红包金额尽量平均一点
                val = new Random().nextInt(temp/count);
                left = temp - val;
                //判断生成的金额大于0，且剩余的钱数够剩下的人平分到0.01元
                if(left*1.0/(count-1) >= 1 && val > 0) {
                    if(max!=null){
                        //如果分配的红包金额大于每个红包金额的上限，则重新分配
                        if(val>max*100){
                            continue;
                        }

                        //如果剩下的金额大于剩余红包的单个上限金额的总和，则重新分配
                        //防止出现某些红包的金额过大的情况
                        if(left>max*100*(count-1)){
                            continue;
                        }

                    }

//                    System.out.println("生成金额 ：" + val + "剩余金额 ：" + left + "剩余人数 ：" + (count-1));
                    break;
                }
            }
            temp = temp - val;
        }
        count--;
        return val/100.0;
    }


    public Double getTotal() {
        return total;
    }

    public void setTotal(Double total) {
        this.total = total;
    }

    public int getTemp() {
        return temp;
    }

    public void setTemp(int temp) {
        this.temp = temp;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}
